<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 搜索部分 -->
      <el-row>
        <el-col :span="9" class="user-col-info">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="userQuerySearch"
            clearable
            @clear="isClear"
          >
            <el-button slot="append" icon="el-icon-search" @click="searchUserList()"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogFormVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- table部分 -->
      <el-table :data="userTableData" border stripe style="width: 100%">
        <el-table-column prop="name" label="#" type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="150px"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="changeState(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editUser(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.id)"
            ></el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userQuery.pagenum"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="userQuery.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户面板 -->
    <el-dialog title="添加用户" :visible.sync="dialogFormVisible" @close="cancleUser()">
      <el-form
        label-width="80px"
        size="medium"
        :rules="userRuleForm"
        :model="userForm"
        ref="userRefForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="userForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="userForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancleUser()">取 消</el-button>
        <el-button type="primary" @click="addUserForm('userRefForm')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑用户面板 -->
    <el-dialog title="编辑用户" width="50%" :visible.sync="editFormVisible" @close="editDialogClose">
      <el-form
        label-width="70px"
        size="medium"
        :rules="editFormRules"
        :model="editForm"
        ref="editFormRef"
      >
        <el-form-item label="用户名">
          <el-input disabled v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogClose()">取 消</el-button>
        <el-button type="primary" @click="editUserInfo()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    var checkEmail = (rule, value, callback) => {
      // 邮箱验证正则表达式
      var regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        callback()
      }
      callback(new Error('请输入正确的邮箱'))
    }
    var checkMobile = (rule, value, callback) => {
      // 手机验证正则表达式
      var regMobile = /^1[3456789]\d{9}$/
      if (regMobile.test(value)) {
        callback()
      }
      callback(new Error('请输入正确的手机号'))
    }
    return {
      userTableData: [],
      userQuery: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      // 总条数
      total: 0,
      // 搜索框内容
      userQuerySearch: '',
      //   控制添加用户面板的显示隐藏
      dialogFormVisible: false,
      // 控制编辑用户面板的显示隐藏
      editFormVisible: false,
      // 添加用户的表单数据
      userForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 编辑表单的数据
      editForm: {},
      // 添加用户的表单验证
      userRuleForm: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [{ validator: checkEmail, required: true, trigger: 'blur' }],
        mobile: [{ validator: checkMobile, required: true, trigger: 'blur' }]
      },
      // 编辑用户的表单验证
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    //   获取用户列表
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.userQuery
      })
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.total = res.data.total
      this.userTableData = res.data.users
    },
    // 当每页显示条数改变时
    handleSizeChange(val) {
      this.userQuery.pagesize = val
      this.getUserList()
    },
    // 当当前页改变时
    handleCurrentChange(val) {
      this.userQuery.pagenum = val
      this.getUserList()
    },
    // 点击搜索按钮
    searchUserList() {
      this.userQuery.query = this.userQuerySearch
      this.getUserList()
    },
    // 是否清空搜索框
    isClear() {
      this.userQuery.query = ''
      this.getUserList()
    },
    // 添加用户面板点击取消
    cancleUser() {
      // 1.关闭dialog面板
      this.dialogFormVisible = false
      // 2.清除数据并且移除验证效果
      this.$refs.userRefForm.resetFields()
    },
    // 点击添加用户按钮
    addUserForm(userRefForm) {
      this.$refs[userRefForm].validate(async valid => {
        if (valid) {
          // 验证通过
          const { data: res } = await this.$http.post('users', this.userForm)
          if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
          // 关闭dialog面板
          this.dialogFormVisible = false
          this.$message.success('添加用户成功')
          // console.log(res)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 改变table用户状态
    async changeState(state) {
      const { data: res } = await this.$http.put(
        `users/${state.id}/state/${state.mg_state}`
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
    },
    // 点击编辑图标
    async editUser(id) {
      this.editFormVisible = true
      const { data: res } = await this.$http.get('users/' + id)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editForm = res.data
    },
    // 编辑用户取消，关闭按钮
    editDialogClose() {
      this.$refs.editFormRef.resetFields()
      this.editFormVisible = false
    },
    // 编辑用户确定按钮
    editUserInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.put(
            'users/' + this.editForm.id,
            { email: this.editForm.email, mobile: this.editForm.mobile }
          )
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.editFormVisible = false
          this.getUserList()
          this.$message.success('编辑用户成功')
          // console.log(res)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 删除用户
    async deleteUser(id) {
      const dle = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(() => {})
      console.log(dle)
      if (dle === 'confirm') {
        const { data: res } = await this.$http.delete('users/' + id)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getUserList()
      }
    }
  },
  created() {
    this.getUserList()
  }
}
</script>
<style lang="less" scoped>
.user-col-info {
  margin-right: 15px;
}
.el-dialog {
  font-size: 15px !important;
}
</style>
